//
//  KoiUserLocalData.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 17.03.25.
//

import Foundation
class KoiUserLocalData {
    private static let userDefaults = UserDefaults.standard
    private static let user_data_pref = "login_user_data"
    private static let last_user_data_pref = "login_last_user_data"
    
    static func saveUser(user:KoiAccountingUser?) {
        if (user == nil) {
            return
        }
        if let jsonData = try? JSONEncoder().encode(user) {
            if let jsonStr = String(data: jsonData,encoding: .utf8) {
                userDefaults.set(jsonStr, forKey: user_data_pref)
            }
        }
    }
    
    static func getUser() -> KoiAccountingUser? {
        let jsonStr = userDefaults.string(forKey: user_data_pref)
        if let jsonData = jsonStr?.data(using: .utf8) {
            if let user = try? JSONDecoder().decode(KoiAccountingUser.self, from: jsonData) {
                return user
            }
        }
        return nil
    }
    
    static func removeUser() {
        userDefaults.removeObject(forKey: user_data_pref)
    }
    
    static func saveLastLoginUser() {
        let userString = userDefaults.string(forKey: user_data_pref)
        userDefaults.set(userString, forKey: last_user_data_pref)
    }
}
